<template>
  <div class="app">
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>考评管理</a-breadcrumb-item>
      <a-breadcrumb-item>事件考评</a-breadcrumb-item>
    </a-breadcrumb>
    <a-row>
      <a-col :span="4">
        所属组织：
        <a-cascader
          style="width: 150px; marigin-left: 10px"
          :options="fzroptions"
          :load-data="loadData"
          placeholder="请选择"
          change-on-select
          @change="selectFzr"
        />
      </a-col>

      <a-col :span="4">
        问题类型：
        <a-select
          placeholder="请选择问题类型"
          v-model="queryForm.issueType"
          style="width: 150px; marigin-left: 10px"
        >
          <a-select-option
            v-for="item in issueTypeData"
            :key="item.value"
            :value="item.value"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-col>

      <a-col :span="4">
        问题对象：
        <a-input
          placeholder="请输入问题对象"
          v-model="queryForm.relatedObjectName"
          style="width: 150px; marigin-left: 10px"
        />
      </a-col>
      <a-col :span="12">
        考评时间范围：
        <a-range-picker
          v-model="creationDateRange"
          @change="changeDate"
          style="width: 250px; marigin-left: 10px"
        />
      </a-col>
      <a-col :span="4">
        <a-button type="primary" @click="handleSearch"> 搜索 </a-button
        >&emsp;&nbsp;
        <a-button>重置</a-button>
      </a-col>
    </a-row>
    <a-spin :spinning="loading">
      <a-row>
        <div class="btn_box">
          <div>业务评分</div>
        </div>
        <a-col :span="24">
          <div class="flex-between">
            <a-tabs v-model="tabsValue" @change="callback">
              <a-tab-pane
                v-for="item in menuList"
                :key="item.value"
                :tab="item.label"
              >
              </a-tab-pane>
            </a-tabs>
            <div class="flex gap-10">
              <a-button
                :disabled="this.selectedRowKeys.length < 1"
                type="primary"
                @click="handleOperation('Task')"
                >抽查部门任务
              </a-button>
              <a-button
                :disabled="this.selectedRowKeys.length < 1"
                type="primary"
                @click="handleOperation('Dispatch')"
                >下发给评价人
              </a-button>
              <a-button
                :disabled="this.selectedRowKeys.length < 1"
                type="primary"
                @click="handleOperation('Setting')"
                >评分设置
              </a-button>
            </div>
          </div>
          <a-table
            class="table"
            :columns="columns"
            :data-source="tableData"
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }"
          >
            <span slot="action" slot-scope="text, record">
              <a class="blue" @click="detailFn(record)">查看</a>
              <a-divider type="vertical" v-if="!text.kpStatus"/>
              <a
                v-hasPermi="['sjkp:rate']"
                v-if="!text.kpStatus"
                class="blue"
                @click="rateScore(text, record)"
                >评分</a
              >
              <a-divider type="vertical" />
              <a
                v-hasPermi="['sjkp:appeal']"
                class="blue"
                @click="complaintFn(text, record)"
                >申诉</a
              >
              <a-divider type="vertical" />
              <a
                class="red"
                @click="deleteFn(text, record)"
                >删除</a
              >
            </span>
          </a-table>
          <div class="page_box">
            <a-pagination
              v-model="queryForm.offset"
              :page-size-options="['20', '30', '40', '50']"
              :total="total"
              show-size-changer
              :page-size="queryForm.current"
              @showSizeChange="onShowSizeChange"
              @change="pageChange"
              :show-total="(total) => `共 ${total} 条`"
            ></a-pagination>
          </div>
        </a-col>
      </a-row>
    </a-spin>

    <a-modal
      :title="dialogTitle"
      :visible="dialogVisible"
      cancel-text="取消"
      ok-text="确认"
      width="38%"
      @cancel="dialogVisible = false"
      @ok="put"
    >
      <div v-if="type == 'Rate'">
        <a-rate v-model="rate" />
      </div>
      <div v-if="type == 'Complaint'">
        <a-form :form="form">
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="申诉情形"
          >
            <a-select
              v-decorator="[
                'appealType',
                { rules: [{ required: true, message: '请选择申诉情形' }] },
              ]"
              placeholder="请选择申诉情形"
              style="width: 100%"
            >
              <a-select-option
                v-for="(item, index) in appealTypeList"
                :key="index"
                :value="item.dictValue"
              >
                {{ item.dictLabel }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="申诉理由"
          >
            <a-textarea
              v-decorator="[
                'appealDesc',
                { rules: [{ required: true, message: '请填写申诉理由' }] },
              ]"
              :rows="4"
              placeholder="请填写申诉理由"
              style="width: 100%"
            />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { Get } from "@/api/request";
import { message } from "ant-design-vue";
import moment from "moment";
import dayjs from "dayjs";
const columns = [
  {
    title: "考评ID",
    dataIndex: "id",
    key: "id",
    width: 100,
  },
  {
    title: "抽查人员",
    dataIndex: "userName",
    key: "userName",
    width: 100,
  },
  {
    title: "所属组织",
    dataIndex: "deptName",
    key: "deptName",
    width: 170,
  },
  {
    title: "职位",
    dataIndex: "postName",
    key: "postName",
    width: 100,
  },
  {
    title: "工作类型",
    dataIndex: "relatedActionTypeName",
    key: "relatedActionTypeName",
    width: 100,
  },
  {
    title: "事件ID",
    dataIndex: "eventId",
    key: "eventId",
    width: 100,
  },
  {
    title: "问题对象",
    dataIndex: "issueType",
    key: "issueType",
    width: 100,
  },
  {
    title: "上报时间",
    dataIndex: "reportTime",
    key: "reportTime",
    width: 200,
  },
  {
    title: "完成时间",
    dataIndex: "overTime",
    key: "overTime",
    width: 200,
  },
  {
    title: "考评状态",
    dataIndex: "kpStatusName",
    key: "kpStatusName",
    width: 100,
  },
  {
    title: "考评人",
    dataIndex: "kpUserName",
    key: "kpUserName",
    width: 100,
  },
  {
    title: "考评星级",
    dataIndex: "kpSocre",
    key: "kpSocre",
    width: 100,
  },
  {
    title: "考评时间",
    dataIndex: "kpTime",
    key: "kpTime",
    width: 200,
  },
  {
    title: "操作",
    key: "action",
    width:180,
    scopedSlots: { customRender: "action" },
    fixed: "right",
  },
];

export default {
  data() {
    return {
      dateRange: [],
      tabsValue: null,
      rate: null,
      eventId: null,
      responsibleNetworkUserId: null,
      tableData: [],
      columns,
      loading: true,
      queryForm: {
        current: 20,
        offset: 1,
        flag: null,
        deptId: null,
        postId: null,
        relatedObjectName: null,
        endTime: "",
        startTime: "",
        userId: null,
      },
      total: 0,
      dialogVisible: false,
      selectedRowKeys: [],
      dialogTitle: "",
      id: null,
      menuList: [
        { label: "全部", value: null },
        { label: "未下发", value: 1 },
        { label: "待考评", value: 2 },
        { label: "已考评", value: 3 },
      ],
      formItemLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 19 },
      },
      formTailLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 19, offset: 4 },
      },
      sourceList: [],
      questionTypeList: [],
      inspectTypeList: [],
      questionLevelList: [],
      appealTypeList: [],
      type: "Rate",
      form: this.$form.createForm(this, { name: "coordinated" }),
      pqId: "",
      listDeptData: [], //所属组织
      listPostData: [], //岗位
      relatedObjectList: [],
      fzroptions: [],
      issueTypeData: [
        { name: "基础设施问题", value: "INFRASTRUCTURE_ISSUES" },
        { name: "环境卫生问题", value: "ENVIRONMENTAL_SANITATION_ISSUES" },
        { name: "安全管理问题", value: "SAFETY_MANAGEMENT_ISSUES" },
        { name: "商业秩序问题", value: "COMMERCIAL_ORDER_ISSUES" },
        { name: "文化保护问题", value: "CULTURAL_PROTECTION_ISSUES" },
        { name: "游客服务问题", value: "TOURIST_SERVICES_ISSUES" },
        { name: "生态环境问题", value: "ECOLOGICAL_ENVIRONMENT_ISSUES" },
      ],
      creationDateRange: [],
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    handleSearch() {
      this.queryForm.offset = 1;
      this.getList();
    },
    // 分页
    onShowSizeChange(current, pageSize) {
      this.queryForm.current = pageSize;
      this.queryForm.offset = 1;
      this.getList();
    },
    pageChange(current) {
      this.queryForm.offset = current;
      this.getList();
    },
    // ----获取部门
    getListDept() {
      var q1 = "government-platform-center/dept?offset=1&current=100";
      this.$axios.get(q1).then((res) => {
        if (res.data.msg == "success") {
          var data = res.data.data;
          this.fzroptions = [];
          for (let i = 0; i < data.length; i++) {
            this.fzroptions.push({
              value: data[i].thisData.deptId,
              label: data[i].thisData.deptName,
              children: [],
            });
            for (let j = 0; j < data[i].childList.length; j++) {
              this.fzroptions[i].children.push({
                value: data[i].childList[j].thisData.deptId,
                label: data[i].childList[j].thisData.deptName,
                isLeaf: false,
              });
            }
          }
        }
      });
    },
    // ----获取职位
    getListpost() {
      console.log("111");
      if (!this.queryForm.deptId) {
        message.warning("请先选择部门");
        return;
      }
      const url = "/government-platform-center/post";
      const params = {
        current: 999,
        offset: 1,
        deptId: this.queryForm.deptId,
      };
      this.$axios
        .get(url, {
          params: params,
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.listPostData = res.data.data;
          }
        });
    },
    selectFzr(e) {
      console.log(e);
      if (e.length == 3) {
        var item = e[2].split("/**/");
        this.queryForm.deptId = e[1]; // 部门
        this.queryForm.postId = item[0]; // 岗位
        this.queryForm.userId = item[1]; //用户ID
        console.log(item);
      }
    },
    //
    loadData(selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      var q =
        "/government-platform-center/dept/getUserListByDeptId?deptId=" +
        targetOption.value;
      this.$axios
        .get(q)
        .then((res) => {
          if (res.data.msg == "success") {
            targetOption.loading = false;
            targetOption.children = [];
            for (let i = 0; i < res.data.data.length; i++) {
              targetOption.children.push({
                label: res.data.data[i].userName,
                value:
                  res.data.data[i].postId + "/**/" + res.data.data[i].userId,
              });
            }
            this.fzroptions = [...this.fzroptions];
          } else {
            targetOption.loading = false;
            this.$message.error(res.data.msg || "加载数据失败");
          }
        })
        .catch((err) => {
          targetOption.loading = false;
          this.$message.error("加载数据失败：" + (err.message || "未知错误"));
        });
    },
    //勾选
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    async init() {
      // await this.getDict1()
      // await this.getDict5();//关联对象
      await this.getDict2(); //问题类型
      // await this.getDict3();// 巡查类型
      await this.getDict4(); //问题等级
      await this.getListDept(); //部门
      // await this.getDict5();//
      await this.getList();
    },
    getList() {
      this.loading = true;
      const url = "government-platform-center/kpiRecord/queryByPagePd";
      const data = this.queryForm;
      this.$axios
        .get(url, {
          params: data,
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.tableData = res.data.data;
            this.total = res.data.total;
            this.loading = false;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    addFn(text, record) {
      this.dialogVisible = true;
      this.form.resetFields();
      this.id = null;
    },
    detailFn(text) {
      this.$router.push({
        path: "/duban/sjdetail",
        query: {
          id: text.eventId,
          operationType: "Detail",
          pageType: "Sjkp",
          // paramId: row[this.pageData.paramId],
        },
      });
    },
    // detailFn(text, type) {
    //   this.$router.push({
    //     path: "/xuncha/zhsldd/detail",
    //     query: {
    //       id: text.eventId,
    //       operationType: "Detail",
    //       pageType: "Ducha",
    //       // paramId: row[this.pageData.paramId],
    //     },
    //   });
    // },
    handleOperation(type) {
      switch (type) {
        case "Setting":
          this.type = "Rate";
          this.dialogTitle = "请评分";
          this.dialogVisible = true;
          break;
        case "Dispatch":
          break;
        case "Task":
          break;
      }
    },
    rateScore(text) {
      this.eventId = text.eventId;
      this.pqId = text.pqId;
      this.responsibleNetworkUserId = text.responsibleNetworkUserId;
      this.type = "Rate";
      this.dialogTitle = "请评分";
      this.dialogVisible = true;
    },
    complaintFn(text) {
      this.eventId = text.eventId;
      this.responsibleNetworkUserId = text.responsibleNetworkUserId;
      this.type = "Complaint";
      this.dialogTitle = "确定发起申述？";
      this.dialogVisible = true;
    },
    put() {
      if (this.type == "Complaint") {
        this.form.validateFields((err, values) => {
          if (err) {
            return;
          }
          const url = "/government-platform-center/kpiAppeal";
          const form = {
            deptId: "1",
            dkrId: "1",
            kpStatus: 2,
            userId: "1",
            appealUserId: "102",
            isAppeal: 0,
            ...values,
          };
          this.$axios
            .post(url, form, {
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
            })
            .then((res) => {
              if (res.data.code == 0) {
                this.dialogVisible = false;
                this.getList();
              }
            });
        });
      }
      if (this.type == "Rate") {
        const url = "/government-platform-center/kpiRecord";
        const form = {
          kpSocre: this.rate,
          eventId: this.eventId,
          pqId: this.pqId,
          kpStatus: 0,
          kpUserId: "100",
          userId: "100",
          // kpUserName: '超级管理员',
          isAppeal: 0,
        };
        this.$axios
          .post(url, form, {
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
          })
          .then((res) => {
            if (res.data.code == 0) {
              message.success("评分成功");
              this.dialogVisible = false;
              this.getList();
            }
          });
      }
    },
    //字典
    //问题来源
    async getDict1() {
      const url =
        "government-platform-center/dictData/queryByCode?dictType=QUESTION_SOURCE_CODE";
      const res = await this.$axios.get(url);
      if (res.data.code == 0) {
        this.sourceList = res.data.data;
      }
    },
    //问题类型
    async getDict2() {
      const url =
        "government-platform-center/dictData/queryByCode?dictType=QUESTION_TYPE_CODE";
      const res = await this.$axios.get(url);
      if (res.data.code == 0) {
        this.questionTypeList = res.data.data;
      }
    },
    //巡查类型
    async getDict3() {
      const url =
        "government-platform-center/dictData/queryByCode?dictType=INSPECTION_TYPE_CODE";
      const res = await this.$axios.get(url);
      if (res.data.code == 0) {
        this.inspectTypeList = res.data.data;
      }
    },
    //问题等级
    async getDict4() {
      const url =
        "government-platform-center/dictData/queryByCode?dictType=QUESTION_LEVE_CODE";
      const res = await this.$axios.get(url);
      if (res.data.code == 0) {
        this.questionLevelList = res.data.data;
      }
    },

    //关联对象
    // async getDict5() {
    //   this.loading = true
    //   const url1 = 'government-platform-center/dictData/queryByCode?dictType=yichan_code';
    //   const res1 = await this.$axios.get(url1);
    //   const url2 = 'government-platform-center/dictData/queryByCode?dictType=merchant_code';
    //   const res2 = await this.$axios.get(url2)
    //   if (res1.data.code == 0 && res2.data.code == 0) {
    //     let data = [...res1.data.data, ...res2.data.data]
    //     console.log()
    //     this.relatedObjectList = this.formatData(data)
    //   }
    // },
    formatData(data) {
      return data.map((ele) => {
        return {
          ...ele,
          value: ele.dictValue,
          label: ele.dictLabel,
        };
      });
    },
    getName(id, list) {
      let name = "";
      list.forEach((item) => {
        if (id == item.dictValue) {
          name = item.dictLabel;
        }
      });
      return name;
    },
    callback(e) {
      this.queryForm.flag = e;
      this.getList();
    },
    deleteFn(text, record) {
      const that = this;
      this.$confirm({
        title: "确认删除",
        content: "确定要删除此记录吗？",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          that.loading = true;
          const url = `/government-platform-center/kpiRecord/${text.id}`;
          that.$axios
            .delete(url)
            .then((res) => {
              that.loading = false;
              if (res.data.code == 0) {
                that.$message.success("删除成功");
                that.getList();
              } else {
                that.$message.error(res.data.msg || "删除失败");
              }
            })
            .catch(() => {
              that.loading = false;
              that.$message.error("删除失败");
            });
        },
      });
    },
    changeDate(val) {
      console.log(val, "val");
      this.queryForm.startTime = dayjs(val[0]).format("YYYY-MM-DD hh:mm:ss");
      this.queryForm.endTime = dayjs(val[1]).format("YYYY-MM-DD hh:mm:ss");
    },
  },
};
</script>
<style scoped>
.ant-row {
  border-radius: 5px;
  margin-bottom: 15px;
  background: #fff;
  padding: 20px;
  color: #000;
}

.flex {
  display: flex;
}

.gap-10 {
  gap: 10px;
}

.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

::v-deep .ant-table-thead > tr > th {
  color: #000;
  font-weight: bold;
}

::v-deep .ant-table-tbody > tr > td {
  color: #000;
}

.ant-col {
  margin: 10px 0;
}

.ant-select {
  width: 60%;
}

.ant-input {
  width: 60%;
}

.blue {
  color: #0052d9;
}

.red {
  color: #ff4d4f;
}

.table {
  width: 100%;
  overflow-x: auto !important;
}

/* 添加表格原生滚动条样式 */
::v-deep .ant-table-body {
  overflow-x: auto !important;
  /* overflow-y: auto !important; */
  /* max-height: 500px; 设置最大高度，超出时显示垂直滚动条 */
}

/* 确保使用原生滚动条样式 */
::v-deep .ant-table-body::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::v-deep .ant-table-body::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 4px;
}

::v-deep .ant-table-body::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

/* 修复固定列的问题 */
::v-deep .ant-table-fixed-right {
  right: 8px; /* 为滚动条留出空间 */
}
</style>
